Sat May 28 2022
How to remove falsy property values from a JavaScript object
A quick snippet of code showcasing a function I created to remove falsy values from a JavaScript object
Problem
I had an object which contained several falsy values and wanted it cleaned. Let's say it looked like what's below
1const someObject = {2 name: "Kisho",3 familyName: undefined,4 location: "Poland",5 age: null,6};
Solution
A quick function that looks like below
1const removeFalsyProperties = (obj) => {2 // assigns the passed object into a const3 const cleanedObject = obj;4 // Object.keys returns us an array of the keys in the object. eg ['name', 'familyName', 'location', 'age']5 // we loop through this array with forEach and look if each key has a value that is falsy6 Object.keys(cleanedObject).forEach((key) => {7 // if there is a falsy value, we delete that property8 if (!cleanedObject[key]) {9 delete cleanedObject[key];10 }11 });12 // once the loop is complete, we return the object which does not contain anymore falsy values13 return cleanedObject;14};
Result
1const cleanedObject = removeFalsyProperties(someObject);
`cleanedObject` should now look something like this.
1{name: 'Kisho', location: 'Poland'}
Did this help you or do you know of any alternative ways of handling this? Hit me up in the comments below!